using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Xml;
using Soveryn.Commerce.API;
using Soveryn.Commerce.Shared;


/// <summary>
/// This is the base class for the main masterpage of the client website. It handles setting up the site design, widgets, and scripts. It also handles some SEO with data setup and provided by the PageBaseClass.
/// </summary>

namespace Soveryn.Commerce.BaseClasses
{

    public class MasterPageBaseClass : System.Web.UI.MasterPage
    {

        public static string PlatformPath = ConfigurationManager.AppSettings["PlatformPath"];

        //doodad specific
        public ArrayList DoodadContainerList = new ArrayList();
        public ArrayList DoodadList = new ArrayList();

        //scripts
        private ArrayList ScriptList = new ArrayList();

        //css
        private ArrayList CSSFileList = new ArrayList();

        //page data
        public DataSet PageList;
        public XmlDocument PageListXML;
        public PageBaseClass ChildPage;
        public ArrayList PageTrail = new ArrayList();
        public String CategoryIDTrail = "";

        //header
        public Literal MetaLiteral;
        public Literal CSSLiteral;
        public Literal ScriptLiteral;
        public Literal HeadScriptsLiteral;
        public Literal AboveBodyEndScriptsLiteral;
        public PlaceHolder BodyStartPlaceHolder;
        public HtmlGenericControl DoodadCanvas;
        public ContentPlaceHolder MasterContentPlaceHolder;

        protected void Page_Init(object sender, EventArgs e)
        {

            ChildPage = (PageBaseClass)this.Page;

        }

        public void RegisterScript(string scriptFile)
        {

            if (ScriptList.Contains(scriptFile.ToUpper()))
                return;

            ScriptList.Add(scriptFile);

        }

        public void RegisterCSSFile(string cssFile)
        {

            if (CSSFileList.Contains(cssFile.ToUpper()))
                return;

            CSSFileList.Add(cssFile);

        }

        public String GetPagePropertyFromXML(XmlElement element, String field)
        {

            if (element != null && element.SelectSingleNode(field) != null && element.SelectSingleNode(field).InnerText != null)
                return element.SelectSingleNode(field).InnerText;
            else
                return "";

        }

        protected void Page_Load(object sender, EventArgs e)
        {

            //get controls in the master page .master
            MetaLiteral = (Literal)Master.FindControl("MetaLiteral");
            CSSLiteral = (Literal)Master.FindControl("CSSLiteral");
            ScriptLiteral = (Literal)Master.FindControl("ScriptLiteral");
            HeadScriptsLiteral = (Literal)Master.FindControl("HeadScriptsLiteral");
            AboveBodyEndScriptsLiteral = (Literal)Master.FindControl("AboveBodyEndScriptsLiteral");
            DoodadCanvas = (HtmlGenericControl)Master.FindControl("DoodadCanvas");
            BodyStartPlaceHolder = (PlaceHolder)Master.FindControl("BodyStartPlaceHolder");
            MasterContentPlaceHolder = (ContentPlaceHolder)Master.FindControl("MasterContentPlaceHolder");

            //load edit mode specific stuff
            if (ChildPage.EmployeeLoggedIn)
            {

                RegisterCSSFile(PlatformPath + "cms/cms.css");
                RegisterScript(PlatformPath + "cms/cms.js");

                RegisterScript(PlatformPath + "platform/jqueryui/jquery-ui.min.js");
                RegisterCSSFile(PlatformPath + "platform/jqueryui/jquery-ui.css");

                ControlBaseClass EditModeToolBar = (ControlBaseClass)LoadControl("~/Controls/EditModeToolBar.ascx");
                BodyStartPlaceHolder.Controls.Add(EditModeToolBar);

                if (ChildPage.EditMode)
                {
                    RegisterCSSFile(PlatformPath + "platform/fontawesome/font-awesome.css");
                    RegisterScript(PlatformPath + "platform/hallo.js");
                }

            }

            //setup page 
            SetupPage();

            //set template style
            DoodadCanvas.Attributes["class"] += " " + ChildPage.Properties.TemplateLayoutTypeInherited;

            if (ChildPage.EmployeeLoggedIn)
                DoodadCanvas.Attributes["style"] = "margin-top:38px;";

            //set doodads
            SetDoodads(DoodadCanvas);

            //set meta data
            MetaLiteral.Text = "";
            MetaLiteral.Text += "<meta name='description' content='" + Server.HtmlEncode(ChildPage.Properties.PageHeadDescription) + "'/>";
            MetaLiteral.Text += "<meta name='keywords' content='" + Server.HtmlEncode(ChildPage.Properties.PageHeadKeywords) + "'/>";

            //add registered css
            CSSLiteral.Text = "";
            foreach (string cssFile in CSSFileList)
                CSSLiteral.Text += "<link href='" + cssFile + "' rel='stylesheet' type='text/css' />";

            //add registered scripts
            ScriptLiteral.Text = "";
            foreach (string script in ScriptList)
                ScriptLiteral.Text += "<script type='text/javascript' src='" + script + "'></script>";

            //add aloha editor
            if (ChildPage.EditMode && ChildPage.EmployeeLoggedIn)
                ScriptLiteral.Text += "<script type='text/javascript'>initHallo();</script>";

            //set header code
            HeadScriptsLiteral.Text = ChildPage.Properties.SEO.HeadScripts + ChildPage.Website.HeaderCode;

            //add google analytics code
            if (!String.IsNullOrEmpty(ChildPage.Website.GoogleAnalyticsAccountID))
            {
                string googleCode = MiscUtils.ReadFile(Server.MapPath("~/Misc/GoogleAnalyticsTrackingJS.txt"));
                HeadScriptsLiteral.Text += googleCode.Replace("%GoogleAnalyticsAccountID%", ChildPage.Website.GoogleAnalyticsAccountID);
            }

            //set body end code
            AboveBodyEndScriptsLiteral.Text = ChildPage.Properties.SEO.AboveBodyEndScripts + ChildPage.Website.BodyEndCode;

            //set title tag
            this.Page.Title = ChildPage.Website.HeadTitlePrefix + ChildPage.Properties.SEO.HeadTitle.Trim() + ChildPage.Website.HeadTitleSuffix;

        }

        public void SetupPage()
        {

            //get page list
            PageListXML = WebsiteData.PageList();

            //get page trail
            XmlNode node = PageListXML.SelectSingleNode("//Page[PageID='" + ChildPage.PageID + "']");
            PageProperties page;
            while (node != null)
            {

                if (node.ParentNode == null)
                    break;

                page = PageProperties.Create(node);

                if (page.ParentPageID == 0)
                    break;

                CategoryIDTrail += page.CategoryID + ",";
                PageTrail.Add(page);

                node = node.ParentNode;

            }
            if (CategoryIDTrail.Length > 0)
                CategoryIDTrail = CategoryIDTrail.Remove(CategoryIDTrail.Length - 1);

        }

        public void SetContainers(Control startControl)
        {

            //loop through and find all containers in the canvas
            foreach (Control control in startControl.Controls)
            {

                if (control.Controls.Count > 0)
                    SetContainers(control);

                //ignore this control if it doesn't have an id or is not a div
                if (control.ID == null)
                    continue;

                //ignore this control if it isn't a container
                if (!control.ID.ToUpper().StartsWith("DOODAD_"))
                    continue;

                //get control
                HtmlGenericControl doodadContainer = (HtmlGenericControl)control;
                DoodadContainerList.Add(doodadContainer);

                //add manage product button if we are on a product page
                if (ChildPage.EmployeeLoggedIn && control.ID.ToUpper() == "DOODAD_MIDDLECOLUMNTOP" && ChildPage.ItemID != 0)
                {
                    ControlBaseClass manageProduct = (ControlBaseClass)LoadControl("~/Controls/ManageProduct.ascx");
                    doodadContainer.Controls.Add(manageProduct);
                }

            }


        }

        public void SetDoodads(Control canvas)
        {

            //get containers
            SetContainers(canvas);

            //if there are no doodads on this page get out
            if (!DataUtils.HasRecords(ChildPage.PageDoodadsInstanceListTable))
                return;

            //load all doodads
            for (int i = 0; i < ChildPage.PageDoodadsInstanceListTable.Rows.Count; i++)
            {

                //get this doodads data
                DataRow dataRow = ChildPage.PageDoodadsInstanceListTable.Rows[i];

                //load doodad
                DoodadInstanceProperties doodadProperties = DoodadInstanceProperties.Create(dataRow);
                String path = doodadProperties.DoodadInstanceFolderPath + doodadProperties.DoodadInstanceFolderName;
                DoodadBaseClass doodad = (DoodadBaseClass)LoadControl(path + "/" + doodadProperties.DoodadInstanceFolderName + ".ascx");
                doodad.Properties = doodadProperties;

                //set load order
                doodad.Properties.DoodadInstanceLoadOrder = i + doodad.Properties.DoodadInstanceLoadOrder;

                //register scripts
                if (doodad.Properties.DoodadInstanceScripts != "")
                {

                    String[] scripts = doodad.Properties.DoodadInstanceScripts.Split(',');

                    foreach (string script in scripts)
                    {
                        RegisterScript(DoodadUtils.ReplaceUserVars(script, doodad.Properties, ChildPage.Website));
                    }

                }

                //register css
                if (doodad.Properties.DoodadInstanceCSSFiles != "")
                {

                    String[] cssFiles = doodad.Properties.DoodadInstanceCSSFiles.Split(',');

                    foreach (string file in cssFiles)
                    {
                        RegisterCSSFile(DoodadUtils.ReplaceUserVars(file, doodad.Properties, ChildPage.Website));
                    }

                }

                //add doodad to list
                DoodadList.Add(doodad);

                //add doodad to placeholder
                Control container;
                Control doodadOrphanContainer = canvas.FindControl("DoodadOrphanContainer");

                //get container
                container = canvas.FindControl(doodad.Properties.DoodadInstanceContainerID);
                if (container == null)
                    container = MasterContentPlaceHolder.FindControl(doodad.Properties.DoodadInstanceContainerID);

                //if the container is found put the doodad in it, otherwise add it to the orphan container
                if (container != null)
                {
                    doodad.Properties.ParentElementID = container.ClientID;
                    doodad.Canvas = container;
                    container.Controls.Add(doodad);
                }
                else
                {
                    if (doodadOrphanContainer != null)
                    {
                        doodad.Properties.ParentElementID = doodadOrphanContainer.ClientID;
                        doodad.Canvas = doodadOrphanContainer;
                        doodadOrphanContainer.Controls.Add(doodad);

                    }
                }

            }

            //set empty containers
            if (ChildPage.EditMode)
            {
                foreach (Control doodadContainer in DoodadContainerList)
                {

                    if (doodadContainer.Controls.Count == 0)
                    {
                        ControlBaseClass doodadPlaceholder = (ControlBaseClass)LoadControl("~/Controls/DoodadPlaceholder.ascx");
                        doodadContainer.Controls.Add(doodadPlaceholder);
                    }

                }
            }

        }

    }

}